<?php

class ConfigController extends Zend_Controller_Action
{
	protected $localConfigPath;
	
	public function init()
	{
		// doctype
		$this->view->doctype('XHTML1_STRICT'); 
		
		// 	get the path to the main fail
		$config = $this->getInvokeArg('bootstrap')->getOption('configs');
		$this->localConfigPath = $config['localConfigPath'];
	}
	
	public function preDispatch()
	{
		// if user admin
		$url = $this->getRequest()->getRequestUri();
		// set layout
		$this->_helper->layout()->setLayout('admin');
		
		if(!Zend_Auth::getInstance()->hasIdentity())
		{
			$session = new Zend_Session_Namespace('zend.auth');
			$session->requesURL = $url;
			$this->_redirect('/admin/login');
		}
	}
	
	/*
	 * 		INDEX
	 */
	public function indexAction()
	{
		$configForm = new Inc_Form_Configure();
		$this->view->form = $configForm;
		
		
		if(file_exists($this->localConfigPath))
		{
			$config = new Zend_Config_Ini($this->localConfigPath);
			
			$data['defaultEmailAddress'] = $config->global->defaultEmailAddress;
			$data['salesEmailAddress'] = $config->user->salesEmailAddress;
			$data['itemsPerPage'] = $config->admin->itemsPerPage;
			$data['displaySellerInfo'] = $config->user->displaySellerInfo;
			$data['logEcxeptionsToFile'] = $config->global->logEcxeptionsToFile;
			
			$configForm->populate($data);
		}
		
		if ($this->getRequest()->isPost())
		{
			if($configForm->isValid($this->getRequest()->getPost()))
			{
				$value = $configForm->getValues();
				
				$config = new Zend_Config(array(), true);
				
				$config->global = array();
				$config->admin = array();
				$config->user = array();
				
				$config->global->defaultEmailAddress = $value['defaultEmailAddress'];
				$config->user->salesEmailAddress = $value['salesEmailAddress'];
				$config->admin->itemsPerPage = $value['itemsPerPage'];
				$config->user->displaySellerInfo = $value['displaySellerInfo'];
				$config->global->logEcxeptionsToFile = $value['logEcxeptionsToFile'];
				
				$writer = new Zend_Config_Writer_Ini();
				$writer->write($this->localConfigPath, $config);
				
				$this->_helper->getHelper('FlashMessenger')->addMessage('Thank you. Your configuration 
						was successrfully saved.');
				$this->_redirect('/admin/config/success');
			}
		}
	}
	
	public function successAction()
	{
		if ($this->_helper->getHelper('flashMessenger')->getMessages())
		{
			$this->view->messages = $this->_helper->getHelper('flashMessenger')
			->getMessages();
		} else {
			$this->_redirect('/');
		}
	}
}